package org.tinygroup.distributed;

import java.util.List;

import javax.sql.DataSource;

import org.springframework.beans.factory.InitializingBean;
import org.tinygroup.commons.tools.Assert;
import org.tinygroup.commons.tools.StringUtil;
import org.tinygroup.sequence.impl.MultipleSequenceDao;
import org.tinygroup.sequence.impl.MultipleSequenceFactory;
import org.tinygroup.tinydb.dialect.impl.MySQLDialect;
import org.tinygroup.tinydb.exception.TinyDbException;

/**
 * 多数据源方式获取分布式主键值
 * @author renhui
 *
 */
public class MultiDistributedMySQLDialect extends MySQLDialect implements
		InitializingBean {

	private List<DataSource> dataSources;

	private String sequenceName;

	private MultipleSequenceFactory sequenceFactory;

	public void setDataSources(List<DataSource> dataSources) {
		this.dataSources = dataSources;
	}

	public void setSequenceName(String sequenceName) {
		this.sequenceName = sequenceName;
	}

	@Override
	public int getNextKey() {
		try {
			return new Long(sequenceFactory.getNextValue(sequenceName))
					.intValue();
		} catch (Exception e) {
			throw new TinyDbException("获取分布式主键值出错", e);
		}
	}

	@Override
	public void afterPropertiesSet() throws Exception {
		Assert.assertTrue(dataSources == null ? false : dataSources.size() > 1,
				"为保证高可用，数据源的个数建议设置多于两个");
		Assert.assertTrue(!StringUtil.isBlank(sequenceName),
				"sequenceName must not null or empty");
		sequenceFactory = new MultipleSequenceFactory();
		MultipleSequenceDao multipleSequenceDao = new MultipleSequenceDao();
		multipleSequenceDao.setDataSourceList(dataSources);
		sequenceFactory.setMultipleSequenceDao(multipleSequenceDao);
		sequenceFactory.init();
	}

}
